import { BrowserWindow, Menu, screen } from "electron";
import path from "node:path";
import { IScreen } from "../types/window";
import { __dirname, publicPath, RENDERER_DIST, VITE_DEV_SERVER_URL } from "../main";

export function createWindow(
  routerPath: string = "login",
  windowWidth = 330,
  windowHeight = 460,
  title: string = "login",
  x?: number,
  y?: number,
): boolean {
  try {
    let win = new BrowserWindow({
      icon: path.join(publicPath, "logo.jpg"),
      width: windowWidth,
      height: windowHeight,
      x,
      y,
      resizable: false,
      frame: false,
      webPreferences: {
        preload: path.join(__dirname, "preload.mjs"),
        contextIsolation: true,
        nodeIntegration: false,
      },
    });
    win.setTitle(title);
    Menu.setApplicationMenu(null);

    if (VITE_DEV_SERVER_URL) {
      win.loadURL(VITE_DEV_SERVER_URL + routerPath).catch(console.error);
      win.webContents.openDevTools();
    } else {
      win
        .loadFile(path.join(RENDERER_DIST, "index.html"), {
          hash: routerPath,
        })
        .catch(console.error);
    }
    win.webContents.on("will-navigate", (event, _url) => {
      // 阻止默认跳转
      event.preventDefault();
    });
    win.webContents.setWindowOpenHandler(() => {
      return { action: "deny" }; // 阻止新窗口
    });
    win.on("close", () => {
      if (title === "home") closeOtherWindows();
      win.removeAllListeners();
    });
    return true;
  } catch (error) {
    console.log("创建失败", error);
    return false;
  }
}

export function closeWindow(title: string) {
  const allWindows = BrowserWindow.getAllWindows();
  const targetWindow = allWindows.find((window) => window.getTitle() === title);
  if (targetWindow) {
    targetWindow.close();
  }
}

export function closeOtherWindows() {
  const allWindows = BrowserWindow.getAllWindows();
  allWindows.forEach((window) => {
    if (window.getTitle() !== "home") {
      window.close();
    }
  });
}

export function closeAllWindows() {
  const allWindows = BrowserWindow.getAllWindows();
  allWindows.forEach((window) => {
    if (window && !window.isDestroyed()) window.close();
  });
}

export function getTargetWindow(title: string): BrowserWindow | null {
  const allWindows = BrowserWindow.getAllWindows();
  const targetWindow = allWindows.find((window) => {
    return window.getTitle() === title;
  });
  if (!targetWindow) {
    console.error(`No window found with title: ${title}`);
    return null;
  }
  return targetWindow;
}

export function getSize(): IScreen {
  const { size, scaleFactor } = screen.getPrimaryDisplay();
  return {
    width: size.width * scaleFactor,
    height: size.height * scaleFactor,
  };
}
